import logging
import time

from django.db import transaction

from libs.auth import check_post_request
from libs.common import error, success
from libs.form import RawJsonForm
from trade.models.member_goods import MemberGoods
from .models import Members, MemberFundLogs

from libs.fund import create_member_fund_log_sn

logger = logging.getLogger(__name__)


# TODO 加入验证
# TODO 根据订单号更新状态


# 充值
def recharge(request):
    form = RawJsonForm(request.body)
    member_sn = form.get('member_sn')
    amount = form.get('amount')
    i_amount = int(amount)
    if not i_amount > 0:
        return error('充值金额必须大于0')
    try:
        mem = Members.objects.get(sn=member_sn)
    except Members.DoesNotExist:
        return error('账号不存在')
    amount_prev = mem.amount
    amount_next = mem.amount + i_amount
    mem.amount = amount_next

    try:
        with transaction.atomic():
            mem.save(update_fields=['amount'])
            member_fund_logs = MemberFundLogs()
            member_fund_logs.sn = create_member_fund_log_sn()
            member_fund_logs.trade_type = 1
            member_fund_logs.amount = i_amount
            member_fund_logs.member_id = mem.id
            member_fund_logs.amount_prev = amount_prev
            member_fund_logs.amount_next = amount_next
            member_fund_logs.save()
    except Exception as ex:
        logger.error(ex)
        return error('充值失败，请重试')

    return success()


# 提现
def withdraw(request):
    form = RawJsonForm(request.body)
    member_sn = form.get('member_sn')
    amount = form.get('amount')
    i_amount = int(amount)
    if not i_amount > 0:
        return error('提现金额必须大于0')
    try:
        mem = Members.objects.get(sn=member_sn)
    except Members.DoesNotExist:
        return error('账号不存在')
    amount_prev = mem.amount
    amount_next = mem.amount - i_amount
    mem.amount = amount_next
    if amount_next < 0:
        return error('余额不足，无法提现')
    mem.amount = amount_next

    try:
        with transaction.atomic():
            mem.save(update_fields=['amount'])
            member_fund_logs = MemberFundLogs()
            member_fund_logs.sn = create_member_fund_log_sn()
            member_fund_logs.trade_type = 2
            member_fund_logs.amount = i_amount
            member_fund_logs.member_id = mem.id
            member_fund_logs.amount_prev = amount_prev
            member_fund_logs.amount_next = amount_next
            member_fund_logs.save()
    except Exception as ex:
        logger.error(ex)
        return error('充值失败，请重试')

    return success()


# 用户资金
def get_member_fund(request):
    return_code, return_content = check_post_request(request)
    if return_code != 0:
        return return_content
    member_id = return_content
    form = RawJsonForm(request.body)
    goods_sn = form.get('goods_sn')
    funds_amount = 0
    frozen_funds = 0
    try:
        member = Members.objects.filter(id=member_id).values('amount', 'frozen_funds').get()
        funds_amount = member['amount']
        frozen_funds = member['frozen_funds']
        mem_goods = MemberGoods.objects.filter(
            member_id=member_id, goods_sn=goods_sn
        ).values('amount', 'frozen_amount').get()
        goods_amount = mem_goods['amount']
        frozen_amount = mem_goods['frozen_amount']
    except MemberGoods.DoesNotExist:
        goods_amount = 0
        frozen_amount = 0
    except Members.DoesNotExist:
        return error()
    data = {
        'goods_amount': goods_amount,
        'frozen_amount': frozen_amount,
        'funds_amount': funds_amount,
        'frozen_funds': frozen_funds,
    }
    return success(data)
